package com.fanghuaman.auth.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fanghuaman.auth.mapper.UserMapper;
import com.fanghuaman.auth.service.AuthService;
import com.fanghuaman.model.auth.dto.AuthParamsDto;
import com.fanghuaman.model.auth.pojo.UserExt;
import com.fanghuaman.model.user.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/**
 * @author shiminghui
 * @date 2024/12/1 18:15
 * @description: TODO
 */
@Component("password_AuthService")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Override
    public UserExt auth(AuthParamsDto authParamsDto) {
        User user = userMapper.selectOne(Wrappers.lambdaQuery(User.class).eq(User::getUsername, authParamsDto.getUsername()));
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }

        UserExt userExt = new UserExt();
        BeanUtils.copyProperties(user, userExt);

        //校验密码
        boolean matches = passwordEncoder.matches(authParamsDto.getPassword(), user.getPassword()); //参数1：明文密码，参数2：密文密码
        if (!matches) {
            throw new RuntimeException("账号或密码错误");
        }
        return userExt;
    }
}
